package com.example.star.view.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.star.R;
import com.example.star.api_service.PostApi;
import com.example.star.entity.Post;
import com.example.star.retrofit.ApiClient;
import com.example.star.utils.ImageUploadUtils;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AddPostActivity extends AppCompatActivity {
    private ImageView addPostImage;
    private EditText addPostTitle;
    private EditText addPostContent;
    private Button addPostSubmit;
    private Button addPostCancel;
    private PostApi postApi;
    private String userName;
    private String selectedImagePath;
    private ImageUploadUtils imageUploadUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_post);

        // 从 SharedPreferences 中获取用户 ID
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        userName = sharedPreferences.getString("username", null);

        if (userName == null) {
            Log.e("AddPostActivity", "用户 ID 未找到，请先登录");
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 初始化视图组件
        addPostImage = findViewById(R.id.add_post_image);
        addPostTitle = findViewById(R.id.add_post_title);
        addPostContent = findViewById(R.id.add_post_content);
        addPostSubmit = findViewById(R.id.add_post_submit);
        addPostCancel = findViewById(R.id.add_post_cancel);

        // 初始化 ImageUploadUtils
        imageUploadUtils = new ImageUploadUtils(this, addPostImage);

        // 通过 ApiClient 获取 PostApi 实例
        postApi = ApiClient.getPostApi();

        addPostImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageUploadUtils.startImageUpload();
            }
        });

        // 设置提交按钮点击事件
        addPostSubmit.setOnClickListener(v -> submitPost());

        // 设置取消按钮点击事件
        addPostCancel.setOnClickListener(v -> finish());
    }

    private void submitPost() {
        String image = selectedImagePath;
        String title = addPostTitle.getText().toString().trim();
        String content = addPostContent.getText().toString().trim();

        if (title.isEmpty()) {
            addPostTitle.setError("标题不能为空");
            return;
        }
        if (content.isEmpty()) {
            addPostContent.setError("内容不能为空");
            return;
        }

        // 创建帖子对象并设置用户 ID
        Post post = new Post();
        post.setImageResource(image);
        post.setTitle(title);
        post.setContent(content);
        post.setUserName(userName);

        Call<Void> call = postApi.addPost(post);
        call.enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                if (response.isSuccessful()) {
                    Log.d("AddPostActivity", "Post added successfully");
                    Toast.makeText(AddPostActivity.this, "帖子添加成功", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    Log.e("AddPostActivity", "Failed to add post, code: " + response.code());
                    Toast.makeText(AddPostActivity.this, "帖子添加失败，错误码: " + response.code(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                Log.e("AddPostActivity", "Error: " + t.getMessage());
                Toast.makeText(AddPostActivity.this, "网络错误，请检查网络连接", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        imageUploadUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        imageUploadUtils.onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
        selectedImagePath = imageUploadUtils.getSelectedImagePath();
    }
}